package com.rpj.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.rpj.dao.TeaDao;
import com.rpj.entity.StuDto;
import com.rpj.entity.StuEntity;
import com.rpj.entity.TeaDto;
import com.rpj.entity.TeaEntity;
import com.rpj.service.TeaService;


@Service
public class TeaImpl implements TeaService{
@Autowired
public TeaDao teadao;
	@Override
	public List<TeaEntity> query() {
		// TODO Auto-generated method stub
		return teadao.query();
	}
	@Override
	public int updateTea(String teaname, String teapassword, String teadept, String status, String teaborrowbooknum,
			String teaborrowmaxnum, String teagivebooknum, String data1,String data2,String data3, String teaid) {
		// TODO Auto-generated method stub
		return teadao.updateTea(teaname, teapassword, teadept, status, teaborrowbooknum, teaborrowmaxnum, teagivebooknum, data1,data2,data3,teaid);
	}
	@Override
	public TeaEntity save(TeaEntity e) {
		// TODO Auto-generated method stub
		return teadao.save(e);
	}
	
	@Override
	public List<String> querydept() {
		// TODO Auto-generated method stub
		return teadao.querydept();
	}
	/**
	 * 登陆查询
	 */
	@Override
	
	public TeaEntity tealogin(String teaname,String teapassword) {
		TeaEntity i = teadao.tealogin(teaname, teapassword);
		return i;
	}
	@Override
	public Page<TeaEntity> queryByCondition(TeaDto dto, Pageable pageable) {
		Specification<TeaEntity> spec = getspec(dto);
		return teadao.findAll(spec,pageable);
	}
	
/**
 * 条件拼接方法
 * @param dto
 * @return
 */
	public Specification<TeaEntity> getspec(final TeaDto dto){
		return new Specification<TeaEntity>() {

			public Predicate toPredicate(Root<TeaEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//创建sql表达式
				Predicate p = criteriaBuilder.conjunction();
				//声明表达式集合
				List<Expression<Boolean>> list = p.getExpressions();
				if(dto.getTeaname()!=""&&dto.getTeaname()!=null) {
					list.add(criteriaBuilder.like(root.get("teaname").as(String.class), "%"+dto.getTeaname()+"%"));
				}
				if(dto.getTeadept()!=""&&dto.getTeadept()!=null) {
					list.add(criteriaBuilder.like(root.get("teadept").as(String.class), "%"+dto.getTeadept()+"%"));
				}
				if(dto.getData1()!=""&&dto.getData1()!=null) {
					list.add(criteriaBuilder.like(root.get("data1").as(String.class), "%"+dto.getData1()+"%"));
				}
			
				return p;
			}
		};
	}
}
